package com.ideal.util.file;

import com.alibaba.fastjson.JSON;
import com.ideal.dto.DictInfoDto;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author songfz
 * @Description
 * @Date 2022/7/27
 */
public class IniUtil {


    private static Logger LOG = Logger.getLogger(IniUtil.class);

    /**
     * 读取ini文件有效内容
     * @param path
     * @param pageDtos
     * @return
     */
    public static  String readContext(String path, List<DictInfoDto> pageDtos)  {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)),"UTF-8"))){

            LinkedHashMap<String, LinkedHashMap<String, String>> contexts = new LinkedHashMap<>();

            String context;
            LinkedHashMap<String, String> sectionMap = null;
            while ((context = reader.readLine()) != null){

                if (!StringUtils.hasText(context)) {
                    continue;
                }
                boolean isNote = false;
                // 过滤掉注释
                for (DictInfoDto pageDto : pageDtos) {

                    if (context.startsWith(pageDto.getDictValue())) {
                        isNote = true;
                        break;
                    }
                }
                if (isNote) {
                    continue;
                }


                // 获取配置分段
                if (context.startsWith("[") && context.endsWith("]")) {

                    sectionMap = new LinkedHashMap<>();

                    String sectionName = context.substring(1, context.length() - 1).trim();
                    if (!StringUtils.hasLength(sectionName)) {
                       continue;
                    }
                    //contexts.put(context,sectionMap);
                    contexts.put(sectionName,sectionMap);
                    continue;
                }

            //    读取内容
                int deliPos = context.indexOf("=");

                if (deliPos < 0) {
                    continue;
                }

                String key = context.substring(0, deliPos).trim();

                String value = context.substring(deliPos + 1).trim();

                if (key.startsWith("\"")&&key.endsWith("\"")) {
                    key = key.substring(1, key.length() - 1).trim();
                }

                if (value.startsWith("\"")&&value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1).trim();
                }
                sectionMap.put(key, value);
            }


            return JSON.toJSONString(contexts);
        }catch (Exception e){
            LOG.error(e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 反解析ini文件内容
     * @return
     */
    public static String parse(String contexts){

        if (!StringUtils.hasLength(contexts)) {
            return null;
        }
        StringBuffer sb = new StringBuffer();

        Map<String,Map<String, String>> contentMap = JSON.parseObject(contexts, Map.class);

        for (String sectionName : contentMap.keySet()) {


            sb.append("[").append(sectionName).append("]").append("\r\n");

            Map<String, String> sectionMap =  contentMap.get(sectionName);
            for (Map.Entry<String, String> entry : sectionMap.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\r\n");
            }
        }
        return sb.toString();


    }

    /**
     * ini文本内容解析
     * @param fileContext
     * @return
     */
    public static String textToContext(String fileContext){

        if (!StringUtils.hasLength(fileContext)) {
            throw new RuntimeException("数据异常");
        }
        LinkedHashMap<String, LinkedHashMap<String, String>> contextMap = new LinkedHashMap<>();
        final String[] contexts = fileContext.split("\r\n");

        LinkedHashMap<String, String> sectionMap = null;
        for (String context : contexts) {
            if (!StringUtils.hasLength(context.trim())) {
                continue;
            }
            // 获取配置分段
            if (context.startsWith("[") && context.endsWith("]")) {

                sectionMap = new LinkedHashMap<>();

                String sectionName = context.substring(1, context.length() - 1).trim();
                if (!StringUtils.hasLength(sectionName)) {
                    continue;
                }
                //contextMap.put(context,sectionMap);
                contextMap.put(sectionName,sectionMap);
            }

            //    读取内容
            int deliPos = context.indexOf("=");

            if (deliPos < 0) {
                continue;
            }

            String key = context.substring(0, deliPos).trim();

            String value = context.substring(deliPos + 1).trim();

            if (key.startsWith("\"")&&key.endsWith("\"")) {
                key = key.substring(1, key.length() - 1).trim();
            }

            if (value.startsWith("\"")&&value.endsWith("\"")) {
                value = value.substring(1, value.length() - 1).trim();
            }
            sectionMap.put(key, value);

        }
        return JSON.toJSONString(contextMap);
    }


    /**
     * JSON字符串转集合
     * @param content
     * @return
     */
    public static  Map<String, Map<String, String>> strToJson(String content){
        return  JSON.parseObject( content,LinkedHashMap.class);
    }
    public static void main(String[] args) {
       //String url = "D:\\file\\20220803\\ini文件_version_032454902.ini";
       //
       // List<DictInfoDto> pageDtos = new ArrayList();
       // final DictInfoDto dictInfoDto = new DictInfoDto();
       // dictInfoDto.setDictId(1L);
       // dictInfoDto.setDictValue(";");
       // pageDtos.add(dictInfoDto);
       // final DictInfoDto dictInfoDto1 = new DictInfoDto();
       // dictInfoDto1.setDictId(2L);
       // dictInfoDto1.setDictValue("#");
       // pageDtos.add(dictInfoDto1);
       // final String s = readContext(url, pageDtos);
       // System.out.println(s);
       //
       // System.out.println(parse(s));
        String ss = "\n" +
                "[ECC]\n" +
                "ECR处理期限=3\n" +
                "\n" +
                "CCO=201901,332674,332673\n" +
                "PCO=201375,201699\n" +
                "CCB主席=201573\n" +
                "CCT主任=201963\n" +
                "[制造单位配置]\n" +
                "制造单位=制造中心，成飞，西飞，沈飞，306所，洪都，客服\n" +
                "\n" +
                "[专业配置]\n" +
                "试飞中心=120011\n" +
                "EWIS_ECP=203380,203370,201543\n";
        System.out.println(textToContext(ss));
    }
}
